package com.cgs.mongo.engine;

import com.mongodb.client.MongoCollection;
import org.bson.Document;

/**
 * 操作上下文
 */
public class OperationalContext<TDocument> {

    /**
     * 默认超时时间
     */
    public static final long DEFAULT_TIMEOUT = 10L;
    /**
     * 在引擎中的对象名称
     */
    public static final String COLLECTION_PREFIX = "col";
    /**
     * MongoCollection对象
     */
    private final MongoCollection<TDocument> collection;
    /**
     * 执行脚本
     */
    private final String script;
    /**
     * 超时时间
     */
    private final long timeout;

    public OperationalContext(MongoCollection<TDocument> collection, String script, long timeout) {
        this.collection = collection;
        this.script = autoComplete(script);
        this.timeout = timeout;
    }

    public OperationalContext(MongoCollection<TDocument> collection, String script) {
        this(collection, script, DEFAULT_TIMEOUT);
    }

    /**
     * 自动补全对象名称col
     * @param script 字符串语句
     * @return 补全后的字符串语句
     */
    private String autoComplete(String script) {
        return script.startsWith(COLLECTION_PREFIX) ? script :
                (script.startsWith(".") ? COLLECTION_PREFIX + script : COLLECTION_PREFIX + "." + script);
    }

    public MongoCollection<TDocument> getCollection() {
        return collection;
    }

    public String getScript() {
        return script;
    }

    public long getTimeout() {
        return timeout;
    }
}
